

var connect = function(next){
    var serialport = require("serialport");
    var SerialPort = serialport.SerialPort;
    serialport.list(function (err, ports){
        var found = ports.some(function(p, index, array) {
            if(p.comName.indexOf("usbmodem1") > -1)
            {
                port = p;
                return true;
            }
            return false;
        });
        if(!found){
            reconnectDevice();
            return;
        }
        if(found){
            var sp = new SerialPort("/dev/cu.usbmodem1", {
                baudrate: 115200,
                parser: serialport.parsers.readline("\n"),
                disconnectedCallback: function() {
                    console.log('设备离线');
                    sp = null;
                    reconnectDevice();
                }

            });

            sp.on("open", function (err) {
                if(err){
                   console.log(err) ;
                }
                console.log('设备连接成功');
                console.log('开始测试' );

                sp.on('data', function(data) {
                    console.log( data.toString());
                    if(data.indexOf("PASSED") === 0){
                        console.log("mpu6000 测试通过！");
                        console.log("等待插入下一个设备");
                    }
                    else if(data.indexOf("FAIL") === 0){
                        console.log("mpu6000 测试失败！");
                    }

                });

                console.log('测试 mpu6000');
                sp.write("mpu6000 start \nmpu6000 factorytest\n", function(err, results) {
                    if(err){
                        console.log(err);
                    }
                });
            });

        }


    });
}
connect();

process.on('uncaughtException', function(err) {
    console.log('uncaughtException');
    console.log(err);
});
